package com.workflow.service.impl;

import java.util.Date;
import java.util.List;

import com.common.util.AbstractManager;
import com.common.util.DateHelper;
import com.common.util.PagerModel;
import com.workflow.bean.Exitdept;
import com.workflow.service.ExitdeptService;

public class ExitdeptServiceImpl extends AbstractManager implements
		ExitdeptService {

	public void addExitdept(Exitdept exitdept) {
		StringBuilder exitno = new StringBuilder();
		Long count = 0L;
		String hql = "select count(*) from Exitdept";
		count = (Long) this.getHibernateTemplate().find(hql).get(0);
		count %= 1000L;
		
		Long num = Long.parseLong(DateHelper.dateToStr(new Date(), "yyyyMMddHms"));
		num *= 1000L;		
		num += count;
		
		exitno.append(exitdept.getDepartmentByDeptcode().getDeptcode());
		exitno.append("-TK-");
		exitno.append(num);
		
		exitdept.setExitno(exitno.toString());
		exitdept.setStartdate(new Date());
		
		this.getHibernateTemplate().save(exitdept);
	}

	@SuppressWarnings("unchecked")
	public List<Exitdept> findAllExitdept() {
		String hql = "from Exitdept ex order by ex.departmentByDeptcode.deptcode, ex.exitno ";
		return this.getHibernateTemplate().find(hql);
	}

	public Exitdept findExitdept(String exitno) {
		return (Exitdept) this.getHibernateTemplate().load(Exitdept.class, exitno);
	}

	public PagerModel findExitdeptForPager() {
		String hql = "from Exitdept ex order by ex.departmentByDeptcode.deptcode, ex.exitno ";
		return searchPaginated(hql);
	}

	public PagerModel findExitdeptForPager(String deptcode) {
		if(deptcode == "") {
			return findExitdeptForPager();
		}
		
		String hql = "from Exitdept ex where ex.departmentByDeptcode.deptcode = ? or " +
				"ex.departmentByDepartmentDeptcode.deptcode = ? order by order by ex.exitno ";
		return searchPaginated(hql,new String[]{deptcode,deptcode});
	}

	public void removeExitdept(String exitno) {
		Exitdept exitdept = null;
		
		String hql = "from Exitdetailno ed where ed.exitdept.exitno = ?";
		List list = this.getHibernateTemplate().find(hql,exitno);

		if(list == null || list.size() == 0) {
			exitdept = (Exitdept) this.getHibernateTemplate().load(Exitdept.class, exitno);
			if(exitdept != null ) {
				this.getHibernateTemplate().delete(exitdept);
			}
		}
		else {
			throw new RuntimeException("you shall remove the items of Exitdetailno before with Exitdept exitno:"+exitno);
		}
	}

	public void updateExitdept(Exitdept exitdept) {
		this.getHibernateTemplate().update(exitdept);
	}

}
